#include "receiverui.h"
#include "ui_receiverui.h"
#include "receiverthread.h"

#include <libmqttclient/asyncsubscribe.h>
#include <common.h>
#include <uavtmi/uavtmi.pb.h>

#include <QDebug>

ReceiverUI::ReceiverUI(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ReceiverUI)
{
    ui->setupUi(this);
    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(slotTimeOut()));
    // name must be unique for each subscriber
    m_pSubscrubeCli = new AsyncSubscribe("AsyncSubcriber");
    m_pThread = new ReceiverThread(m_pSubscrubeCli);
    connect(m_pSubscrubeCli,
            SIGNAL(dataRecived(QByteArray,QByteArray)),
            this,
            SLOT(onMesageReceived(QByteArray,QByteArray)));
    for(uint i = uavtable::X; i < uavtable::LASTROW; i++)
    {
        QTableWidgetItem *newItem = new QTableWidgetItem("no data");
        newItem->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget->setItem(i,0, newItem);
    }
}

ReceiverUI::~ReceiverUI()
{
    delete m_pSubscrubeCli;
    delete ui;
}

void ReceiverUI::on_pbStart_clicked()
{
    m_pThread->start();
}


void ReceiverUI::on_pbStop_clicked()
{
    m_pSubscrubeCli->deactivate();
}

void ReceiverUI::slotTimeOut()
{

}

void ReceiverUI::updateTableDatas()
{
}

void ReceiverUI::onMesageReceived(QByteArray ba_topic, QByteArray ba_message)
{
    std::string topic = QString(ba_topic).toStdString();
    std::string message(ba_message.data(), ba_message.size()); // =  QString(ba_message).toStdString();
    telemetry::Navigation navigation;
    qDebug() << topic.data();
    if(navigation.ParseFromString(message))
    {

        ui->tableWidget->item(uavtable::X,0)->setText(QString::number(navigation.x()));
        ui->tableWidget->item(uavtable::Y,0)->setText(QString::number(navigation.y()));
        ui->tableWidget->item(uavtable::Z,0)->setText(QString::number(navigation.z()));
        ui->tableWidget->item(uavtable::ALTITUDE,0)->setText(QString::number(navigation.altitude()));
        ui->tableWidget->item(uavtable::HEIGHT,0)->setText(QString::number(navigation.height()));
    }
}


void ReceiverUI::sendDatas()
{
}
